import { Modal } from "antd";
import { useEffect, useRef, useState } from "react";
import { VariableTree } from "./VariableTree";
import "./index.scss";
import MonacoEditor, { OnMount } from "@monaco-editor/react";
import * as monaco from "monaco-editor";
type EditorRef = Parameters<OnMount>[0];
interface FormulaEditorModalProps {
  visible: boolean;
  value?: string;
  handleOk: (val: string) => void;
  handleCancel: () => void;
}

export function FormulaEditorModal(props: FormulaEditorModalProps) {
  const { visible, handleCancel, value, handleOk } = props;
  const [inputValue, setInputValue] = useState(value);
  const editorRef = useRef<EditorRef>();
  useEffect(() => {
    visible && setInputValue(value);
  }, [visible]);

  function handleModalConfirm() {
    handleOk(inputValue || "");
    handleCancel();
  }
  function handleInsertVariable(val: string) {
    if (editorRef.current) {
      const model = editorRef.current.getModel()!;
      const position = editorRef.current.getPosition()!;
      model.applyEdits([
        {
          range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column),
          text: val,
        },
      ]);
      editorRef.current.focus()
      const text = model.getValue()
      setInputValue(text)
    }
  }

  const handleEditorMount: OnMount = (editor, monaco) => {
    editorRef.current = editor;
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyJ, () => {
      editor.getAction("editor.action.formatDocument")?.run();
    });
  };
  return (
    <Modal
      title="公式编辑器"
      width={800}
      open={visible}
      okText="添加"
      cancelText="取消"
      onOk={handleModalConfirm}
      onCancel={() => {
        handleCancel();
      }}
      centered
      destroyOnClose
      className="modal-formula-editor"
    >
      <div className="flex h-[460px] border rounded">
        <main className="flex flex-col flex-1 w-40">
          <h3 className="columnTitle">
            <span>公式编辑器</span>
            {/* <div><span>展开全部</span> <Switch size="small" onChange={handleSwitch}/></div> */}
          </h3>
          <section className="flex-1 h-10 border py-[5px] pl-[5px]">
            <MonacoEditor
              height={"100%"}
              // path="light"
              language="JavaScript"
              onMount={handleEditorMount}
              value={inputValue}
              options={{
                fontSize: 14,
                scrollBeyondLastLine: false,
                minimap: {
                  enabled: false,
                },
                scrollbar: {
                  verticalScrollbarSize: 12,
                  horizontalScrollbarSize: 6,
                },
              }}
            />
          </section>
        </main>
        <aside className="w-80 border-l-[1px]">
          <VariableTree insertVariable={handleInsertVariable} />
        </aside>
      </div>
    </Modal>
  );
}
